// import { constantRouterMap } from '@/router'
// import { asyncRouterMap } from '../../router/'
// mport { asyncRouterMap } from '@/router'
import { constantRouterMap } from '@/router'
import router from '@/router'
import { getLeftTree } from '@/api/leftTree'
import MenuUtils from '@/utils/menuUtils'
import { getRole } from '@/utils/auth'

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ADDROUTERS: (state, routers) => {
      state.addRouters = routers
      // state.routers = constantRouterMap
      // console.log(JSON.stringify(routers))
      state.routers = constantRouterMap.concat(routers)
      // console.log(state.routers)
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        getLeftTree().then(res => {
          if (res.errorCode === '200') {
            let accessedRouters = []
            MenuUtils(accessedRouters, res.propertyRLst)
            let roles = []
            if (getRole()) {
              roles = JSON.parse(getRole())
            }
            commit('SET_ADDROUTERS', accessedRouters)
            accessedRouters = this.getters.routers
            accessedRouters = filterAsyncRouter(accessedRouters, roles)
            commit('SET_ROUTERS', accessedRouters)
            router.addRoutes(accessedRouters)
          } else {
            alert(res)
          }
        })
        resolve()
      })
    }
  }
}
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.role) {
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
  } else {
    return true
  }
}
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

export default permission
